package com.zheng.api.server.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.zheng.api.common.constant.ApiConstant;
import com.zheng.api.common.constant.ApiResult;
import com.zheng.api.common.constant.ApiResultConstant;
import com.zheng.api.server.util.AES;
import com.zheng.common.constant.Constant;
import com.zheng.common.util.*;
import com.zheng.umbrella.dao.model.*;
import com.zheng.umbrella.rpc.api.UmbrellaHardwareCommunicationfailLogService;
import com.zheng.umbrella.rpc.api.UmbrellaHardwareMachineService;
import com.zheng.umbrella.rpc.api.UmbrellaHardwarePathService;
import com.zheng.upms.rpc.api.UpmsDictService;
import com.zheng.upms.rpc.api.UpmsSystemParamService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service("apiCommonService")
public class ApiCommonService {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ApiCommonService.class);

    /**
     * 缓存模块前缀
     */
    @Value("${Redis.CacheModule}")
    private String cacheModule;
    /**
     *  超时门限(秒)
     */
    private static Integer EXPIRE_TIME = 60 * 60 * 24 * 100;

    @Autowired
    UpmsDictService upmsDictService;
    @Autowired
    UpmsSystemParamService upmsSystemParamService;
    @Autowired
    UmbrellaHardwareMachineService umbrellaHardwareMachineService;
    @Autowired
    UmbrellaHardwarePathService umbrellaHardwarePathService;
    @Autowired
    UmbrellaHardwareCommunicationfailLogService umbrellaHardwareCommunicationfailLogService;

    public ApiResult checkIn(String command,String machineCode, int code, String message, JSONObject recvData) {
        /*
            {
                "command": 20001,
                "machineCode": "2018092700001",
                "code": 1,
                "message": "",
                "data": {
                    "type": 1
                }
            }
         */
        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.FAILED.code,ApiResultConstant.FAILED.message,ApiConstant.UMBRELLA_MACHINE_COMMAND_10001,machineCode,dataInfo);
        try {
            String type = recvData.getString("type");
            if (!StringUtils.isEmpty(machineCode) && !StringUtils.isEmpty(type)) {
                if (type.equals("1")) {

                    UmbrellaHardwareMachineExample example = new UmbrellaHardwareMachineExample();
                    UmbrellaHardwareMachineExample.Criteria criteria = example.createCriteria();
                    criteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL); //数据正常
                    criteria.andStatusNotEqualTo(ApiConstant.UM_MACHINE_STATUS_OFF);//未启用状态
                    criteria.andCodeEqualTo(machineCode);
                    UmbrellaHardwareMachine umbrellaHardwareMachine = umbrellaHardwareMachineService.selectFirstByExample(example);
                    //判断伞机状态
                    if (umbrellaHardwareMachine == null) {
                        result.setCode(ApiResultConstant.VERIFY_MACHINE_UNENABLED.code);
                        result.setMessage(ApiResultConstant.VERIFY_MACHINE_UNENABLED.message);
                        result.setData(dataInfo);
                    } else {
                        //签到既在线
//                        umbrellaHardwareMachine.setStatus(ApiConstant.UM_MACHINE_STATUS_UP);//设为在线状态
//                        umbrellaHardwareMachineService.updateByPrimaryKey(umbrellaHardwareMachine);


                        //根据openid查询skey是否存在
                        String skeyPath = cacheModule + ":" + ApiConstant.UMBRELLA_MACHINE_LOGIN_USER_TOKEN + ":" + machineCode;
                        String skey_redis = RedisUtil.get(skeyPath);
                        if (StringUtil.isEmpty(skey_redis)) {
                            //存在 删除 skey 重新生成skey 将skey返回
                            RedisUtil.remove(skeyPath);
                        }

                        String timestamp = System.currentTimeMillis()+"";

                        int versionType = umbrellaHardwareMachine.getType();//伞机版本

                        //uuid生成唯一key并缓存
                        String uuid = UUID.randomUUID().toString();
                        RedisUtil.set(skeyPath, uuid, EXPIRE_TIME);
                        //加密token
                        String encryptToken = XXTEAUtil.encrypt(uuid, machineCode);
                        //把token返回给签到端
                        dataInfo.put("serialNo", BizSequenceUtils.getInstance().generateBizSeqNo(ModuleConstant.UMBRELLA_COMMON_BIZ_SEQUENCE_NO_PREFIX));
                        dataInfo.put("token", encryptToken);
                        //植入基本配置数据
                        if ( versionType > 1) { //一代机后的版本处理
                            dataInfo.put("timestamp", timestamp);
                            //dataInfo.put("mqttUrl", AESUtil.aesEncode(upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_COMM_MQTTURL_V" + versionType),timestamp));
                            //dataInfo.put("mqttUserName", AESUtil.aesEncode(upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_COMM_MQTTUSERNAME_V" + versionType),timestamp));
                            //dataInfo.put("mqttPassword", AESUtil.aesEncode(upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_COMM_MQTTPASSWORD_V" + versionType),timestamp));
                            //dataInfo.put("topic", AESUtil.aesEncode(upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_COMM_TOPIC_V" + versionType),timestamp));
                            //dataInfo.put("queue", AESUtil.aesEncode(upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_COMM_QUEUE_V" + versionType),timestamp));
                            dataInfo.put("mqttUrl", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_COMM_MQTTURL_V" + versionType));
                            dataInfo.put("mqttUserName",upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_COMM_MQTTUSERNAME_V" + versionType));
                            dataInfo.put("mqttPassword", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_COMM_MQTTPASSWORD_V" + versionType));
                            dataInfo.put("topic", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_COMM_TOPIC_V" + versionType));
                            dataInfo.put("queue", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_COMM_QUEUE_V" + versionType));
                            dataInfo.put("rfid1timeout", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_RFID1TIMEOUT_V" + versionType));
                            dataInfo.put("rfid2timeout", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_RFID2TIMEOUT_V" + versionType));
                            dataInfo.put("smartsenstimeout", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_SMARTSENSTIMEOUT_V" + versionType));
                            dataInfo.put("maintaintimeout", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_MAINTAINTIMEOUT_V" + versionType));
                        } else {
                            dataInfo.put("mqttUrl", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_COMM_MQTTURL"));
                            dataInfo.put("mqttUserName", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_COMM_MQTTUSERNAME"));
                            dataInfo.put("mqttPassword", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_COMM_MQTTPASSWORD"));
                            dataInfo.put("topic", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_COMM_TOPIC"));
                            dataInfo.put("queue", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_COMM_QUEUE"));
                            dataInfo.put("rfid1timeout", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_RFID1TIMEOUT"));
                            dataInfo.put("rfid2timeout", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_RFID2TIMEOUT"));
                            dataInfo.put("smartsenstimeout", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_SMARTSENSTIMEOUT"));
                            dataInfo.put("maintaintimeout", upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_MAINTAINTIMEOUT"));
                        }
                        //伞机额定装伞量
                        dataInfo.put("machineCapacity", umbrellaHardwareMachine.getCapacity());
                        //伞机剩余雨伞数量
                        dataInfo.put("machineRemainder", umbrellaHardwareMachine.getRemainder());

                        dataInfo.put("heartBeatRate", Integer.parseInt(upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_HEARTBEATRATE")));

                        //伞道信息
                        UmbrellaHardwarePathExample pathExample = new UmbrellaHardwarePathExample();
                        pathExample.createCriteria().andMachineCodeEqualTo(machineCode);
                        List<UmbrellaHardwarePath> pathList = umbrellaHardwarePathService.selectByExample(pathExample);
                        JSONArray pathInfo = new JSONArray();
                        if (pathList != null && pathList.size() > 0) {
                            for (int i = 0; i < pathList.size(); i++) {
                                JSONObject item = new JSONObject();
                                item.put("pathCode", pathList.get(i).getCode());
                                item.put("pathNumber", pathList.get(i).getNumber());
                                item.put("pathCapacity", pathList.get(i).getCapacity());
                                item.put("pathRemainder", pathList.get(i).getRemainder());
                                pathInfo.add(item);
                            }
                        } else {
                            JSONObject item = new JSONObject();
                            item.put("pathCode", machineCode + "001");
                            item.put("pathNumber", 1);
                            item.put("pathCapacity", 40);
                            item.put("pathRemainder", 0);
                            pathInfo.add(item);
                        }
                        dataInfo.put("pathInfo", pathInfo);
                    /*
                        {
                            "command": 10001,
                            "machineCode": "2018092700001",
                            "code": 1,
                            "message": "",
                            "data": {
                                "serialNo": "20180929100020001",
                                "token": "20180929100020001",
                                "mqttUrl": "tcp://www.bjs-tech.cn:21883",
                                "mqttUserName": "machine",
                                "mqttPassword": "bjsmachine",
                                "topic": "bjs.client.topic.umbrella.machine",
                                "queue": "bjs.server.queue.umbrella.machine",
                                "rfid1timeout": 3,
                                "rfid2timeout": 8,
                                "smartsenstimeout": 5,
                                "maintaintimeout": 90
                            }
                        }
                    */

                        result.setCode(ApiResultConstant.SUCCESS.code);
                        result.setMessage(ApiResultConstant.SUCCESS.message);
                        result.setData(dataInfo);
                    }
                } else {
                    result.setCode(ApiResultConstant.VERIFY_MACHINE_UNENABLED.code);
                    result.setMessage("签到失败,type不正确");
                    result.setData(dataInfo);
                }
            } else {
                result.setCode(ApiResultConstant.FAILED.code);
                result.setMessage("签到失败,参数不正确");
                result.setData(dataInfo);
            }
        }catch (Exception e){
            logger.error("处理通信消息日志失败",e);
        }
        return result;
    }

    public ApiResult notify(String command,String machineCode, int code, String message, JSONObject recvData,String ipAddress) {
        /*
            {
                "command": 20004,
                "machineCode": "2018092700001",
                "code": 1,
                "message": "",
                "data": {
                    "type": 1,
                    "status": 1,// 0建立连接异常，1 建立连接成功
                    "errorMsg"://反馈描述信息或异常信息
                }
            }
         */
        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.FAILED.code,ApiResultConstant.FAILED.message,ApiConstant.UMBRELLA_MACHINE_COMMAND_10004,machineCode,dataInfo);
        try {
            String type = JsonUtil.getString(recvData, "type");
            int status = JsonUtil.getInteger(recvData, "status");
            String errorMsg = JsonUtil.getString(recvData, "errorMsg");

            if (!StringUtils.isEmpty(machineCode) && !StringUtils.isEmpty(type)) {
                if (ApiConstant.UMBRELLA_MACHINE_COMMAND_20004.equals(command)) {
                    if ("1".equals(type)) {
                        Date time = DateUtil.getNowDate();
                        UmbrellaHardwareCommunicationfailLog log = new UmbrellaHardwareCommunicationfailLog();
                        log.setCommand(command);
                        log.setCtime(time);
                        log.setStartTime(time);
                        log.setFlag(1);
                        log.setIp(ipAddress);
                        log.setMachineCode(machineCode);
                        log.setOrderno(BizSequenceUtils.getInstance().generateBizSeqNo(ModuleConstant.UMBRELLA_COMMON_BIZ_SEQUENCE_NO_PREFIX));
                        log.setResult(status);
                        log.setErrormsg(errorMsg);
                        log.setUserid(0);
                        umbrellaHardwareCommunicationfailLogService.insert(log);
                    /*
                        {
                            "command": 10004,
                            "machineCode": "2018092700001",
                            "code": 1,//响应结果(1,成功；0，失败)
                            "message": "",
                            "data": {
                                "machineCode": "2018092700001"
                            }
                        }
                     */
                        dataInfo.put("machineCode", machineCode);

                       /* //更新伞机状态 
                        UmbrellaHardwareMachineExample example = new UmbrellaHardwareMachineExample();
                        UmbrellaHardwareMachineExample.Criteria criteria = example.createCriteria();
                        criteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL); //数据正常
                        criteria.andStatusNotEqualTo(ApiConstant.UM_MACHINE_STATUS_OFF);//未启用状态
                        criteria.andCodeEqualTo(machineCode);
                        UmbrellaHardwareMachine umbrellaHardwareMachine = umbrellaHardwareMachineService.selectFirstByExample(example);
                        if (umbrellaHardwareMachine != null) {
                            //未启用的不更新
                            if (umbrellaHardwareMachine.getStatus() != ApiConstant.UM_MACHINE_STATUS_OFF) {
                                umbrellaHardwareMachine.setStatus(ApiConstant.MACHINE_MQ_CONNECT_SUCCESS.equals(status) ? ApiConstant.UM_MACHINE_STATUS_UP
                                        : ApiConstant.UM_MACHINE_STATUS_FAIL);
                                umbrellaHardwareMachineService.updateByPrimaryKey(umbrellaHardwareMachine);
                            }
                        }*/
                        result.setCode(ApiResultConstant.SUCCESS.code);
                        result.setMessage(ApiResultConstant.SUCCESS.message);
                        result.setData(dataInfo);
                    } else {
                        result.setCode(ApiResultConstant.FAILED.code);
                        result.setMessage("接收通知失败,type不正确");
                        result.setData(dataInfo);
                    }
                } else {
                    result.setCode(ApiResultConstant.FAILED.code);
                    result.setMessage("接收通知失败,command不正确");
                    result.setData(dataInfo);
                }
            } else {
                result.setCode(ApiResultConstant.FAILED.code);
                result.setMessage("接收通知失败,参数不正确");
                result.setData(dataInfo);
            }
        }catch(Exception e){
          logger.error("处理通信消息日志失败",e);
        }
        return result;
    }
}
